<template>
  <div>
    <login-top middleTop="注册bilibili">
      <van-button class="topSwitchBtn" slot="right" type="default" size="mini" @click="$router.push('/login')">登录
      </van-button>
    </login-top>
    <van-form validate-first @failed="onFailed" @submit="registerSubmit">
      <login-text label="用户名" placeholder="请输入用户名" :rules="[{ pattern, message: '用户名长度为6到15位' }]"
                  @inputChange="res => registerForm.name =res"></login-text>
      <login-text label="账号" placeholder="请输入账号" :rules="[{ pattern, message: '账号长度为6到15位' }]"
                  @inputChange="res => registerForm.username =res"></login-text>
      <login-text label="密码" placeholder="请输入密码" type="password" :rules="[{ pattern, message: '密码长度为6到15位' }]"
                  @inputChange="res => registerForm.password =res"></login-text>
      <login-btn btnText="注册"></login-btn>
    </van-form>
  </div>
</template>

<script>
import LoginTop from '@/components/common/LoginTop'
import LoginText from '@/components/common/LoginText'
import LoginBtn from '@/components/common/LoginBtn'

export default {
  name: 'Register',
  data () {
    return {
      // 正则校验规则
      pattern: /^.{6,15}$/,
      // 用户注册表单
      registerForm: {
        name: '',
        username: '',
        password: ''
      }
    }
  },
  methods: {
    // 表单校验
    onFailed (errorInfo) {
      console.log('failed', errorInfo)
      this.$msg.fail('请检查表单填写内容')
    },
    // 点击注册按钮发送请求
    async registerSubmit () {
      const res = await this.$http.post('/register', this.registerForm)
      if (res.status === 200 && res.data.code === 200) {
        this.$msg.success(res.data.msg)
        window.sessionStorage.setItem('id', res.data.id)
        window.sessionStorage.setItem('token', res.data.objtoken)
        setTimeout(() => {
          this.$router.push('/userinfo')
        }, 1000)
      } else {
        this.$msg.fail(res.data.msg)
      }
    }
  },
  components: {
    LoginTop,
    LoginText,
    LoginBtn
  }
}
</script>

<style lang="less" scoped>
.topSwitchBtn .van-button__content {
  font-size: 0.333rem !important;
}
</style>
